package com.interagriculture.aspect;

import com.interagriculture.common.Constants;
import com.interagriculture.common.CustomException;
import com.interagriculture.entity.AdminInfo;
import com.interagriculture.enums.ExceptionCodeEnum;
import com.interagriculture.utils.CacheContainerUtil;
import com.interagriculture.utils.StringTools;
import com.interagriculture.utils.ThreadLocalUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 11 2024/11/12
 */
@Aspect
@Component
public class PermissionCheckAspect {

    @Before("execution(* com.interagriculture.controller.*.*(..)) && @annotation(com.interagriculture.annotation.AdminVerify)")
    public void checkPermission(){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes!=null){
            HttpServletRequest request =
                    attributes.getRequest();
            String session = request.getHeader(Constants.SESSION);
            if(StringTools.isEmpty(session)){
                throw new CustomException(ExceptionCodeEnum.LOGGING_FIRST);
            }
            String account = CacheContainerUtil.getSession(session);
            if(account==null){
                throw new CustomException(ExceptionCodeEnum.ERROR_REQUEST);
            }
            AdminInfo adminInfo = new AdminInfo(session,Integer.parseInt(account));
            ThreadLocalUtil.set(adminInfo);
        }else {
            throw new CustomException(ExceptionCodeEnum.ERROR_REQUEST);
        }
    }
}
